﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Agile.Crm4.Plugins.FilteredLookup
{
    public class FetchXmlAdapter
    {
        private XmlDocument fetchDocument = new XmlDocument();
        public FetchXmlAdapter(string fetchXml)
        {
            fetchDocument.LoadXml(fetchXml);
        }

        public string EntityName
        {
            get
            {
                var attribute = fetchDocument.SelectSingleNode("//entity").Attributes["name"];

                return attribute.Value; ;
            }
        }

        /// <summary>
        /// Inline the additional filter found inside the original fetch xml.
        /// </summary>
        /// <param name="fetchDocument"></param>
        /// <param name="additionalFilter"></param>
        public FetchXmlAdapter InjectFilter(string filter)
        {
            var newFilterNode = fetchDocument.CreateNode(XmlNodeType.Element, "filter", string.Empty);

            var typeAttribute = fetchDocument.CreateAttribute("type");
            typeAttribute.Value = "and";
            newFilterNode.Attributes.Append(typeAttribute);
            newFilterNode.InnerXml = filter;

            var entityNode = fetchDocument.SelectSingleNode(@"fetch//entity");
            var currentFilterNode = entityNode.SelectSingleNode(@"filter");

            if (currentFilterNode != null)
            {
                entityNode.RemoveChild(currentFilterNode);
                newFilterNode.AppendChild(currentFilterNode);
            }

            entityNode.AppendChild(newFilterNode);

            return this;
        }


        public string FetchXml
        {
            get
            {
                return fetchDocument.OuterXml;
            }
        }

    }
}
